package com.only4play.practice.demo.netty.netty1;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

public class ClientHello {
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        NioEventLoopGroup work = new NioEventLoopGroup();
        try {
            bootstrap.group(work)
                    // 选择客户端的Channel实现
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        // 连接建立之后进行初始化，客户端许需要对发送的消息进行编码（服务端则是对接收到的消息进行解码）
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringEncoder());

                        }
                    })
                    // 选择连接到的服务器地址和端口
                    .connect("localhost", 8081)
                    // 执行到这里时会进行等待，连接建立后才往下进行
                    .sync()
                    // 拿到客户端跟服务端的连接对象
                    .channel()
                    .writeAndFlush("hello world")
            ;
        }catch (InterruptedException e) {
            System.out.println("启动异常");
        } finally {
//            work.shutdownGracefully();
                System.out.println("websocket服务器已关闭");
        }
    }
}
